//
//  KKRefreshController.swift
//  KKWeibo
//
//  Created by kassia on 16/7/18.
//  Copyright © 2016年 kassia. All rights reserved.
//

import UIKit

let KKRefreshControlHeight: CGFloat = 50
// 下拉刷新的枚举类型
enum KKRefreshControllerState: Int {
    // 下拉刷新状态
    case Normal = 0
    
    //  松手就刷新状态
    case Pulling = 1
    
    // 正在刷新
    case Refreshing = 2

}
// 自定义下拉刷新控件
class KKRefreshController: UIControl {

    //当前下拉刷新的状态
    private var refreshState: KKRefreshControllerState = .Normal {
        didSet {
        
            switch refreshState {
            
            case .Normal:
                messageLable.text = "下拉刷新"  // 文字内容
                iconImage.hidden = false // 图片显示
                indicator.stopAnimating() // 风火轮关闭
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.iconImage.transform = CGAffineTransformIdentity// 回到初始位置
                })
                
    
            case .Pulling:
                messageLable.text = "松手就刷新"
                
                // 头像旋转的角度
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.iconImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                
                })
                
            case .Refreshing:
                messageLable.text = "正在刷新"
                iconImage.hidden = true
                indicator.startAnimating()
                
                // 向外界发送事件
                sendActionsForControlEvents(.ValueChanged)

            }
        
        }
        
        
    }
    
    // 当前滚动视图
    var currentScrollerView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = RandomColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    
    /// 懒加载控件
    
    // 下拉箭头
    private lazy var iconImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    // 内容lable
    private lazy var messageLable: UILabel = {
    
        let lable = UILabel()
        lable.font = UIFont.systemFontOfSize(12)
        lable.textColor = UIColor.grayColor()
        lable.text = "下拉刷新"
        return lable
    
    }()
    
    // 风火轮
    private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.Gray)
   
    private func setupUI() {
        
        backgroundColor = RandomColor()
        addSubview(iconImage)
        addSubview(messageLable)
        addSubview(indicator)
        
    // 使用系统的约束
        iconImage.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImage, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImage, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        messageLable.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLable, attribute: .Leading, relatedBy: .Equal, toItem: iconImage, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLable, attribute: .CenterY, relatedBy: .Equal, toItem: iconImage, attribute: .CenterY, multiplier: 1, constant: 0))
        
        indicator.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicator, attribute: .CenterX, relatedBy: .Equal, toItem: iconImage, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicator, attribute: .CenterY, relatedBy: .Equal, toItem: iconImage, attribute: .CenterY, multiplier: 1, constant: 0))

    }
    // 将要添加到哪个父控件的时候去调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        //判断其是否能滚动
        guard let scrollView = newSuperview as? UIScrollView else {
        
            return
        
        }
        
           // 代码执行到此视图一定能够滚动
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: KKRefreshControlHeight)
        
        self.frame.origin.y = -KKRefreshControlHeight
        
        // 使用kvo其父控件的滚动
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        
        currentScrollerView = scrollView
    }
    
    // kvo监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        
        guard let scrollerView = currentScrollerView else {
        
            return
        }
        //  1. 如果拖动情况下, 有两种状态 1. 下拉刷新状态 2. 松手就刷新的状态
 
        //  2. 如果松手情况下, 就要进入'正在刷新的状态' 前提(当前的刷新状态 松手就刷新的状态)
     
        if scrollerView.dragging {
        
            if scrollerView.contentOffset.y < -(scrollerView.contentInset.top + KKRefreshControlHeight) && refreshState == .Normal {
            
                print("松手就刷新")
                refreshState = .Pulling
     
            } else if scrollerView.contentOffset.y >= -(scrollerView.contentInset.top + KKRefreshControlHeight) && refreshState == .Pulling {

                print("下拉刷新")
                refreshState = .Normal
            }
        
        } else {
        
           
            if refreshState == .Pulling {
               refreshState = .Refreshing
               print("正在刷新")
            }

        
        }
    }
 
    func endRefreshing() {
        
    refreshState = .Normal
    
    }
    
    
    deinit {
    
        // kvo 
        currentScrollerView?.removeObserver(self, forKeyPath: "contentOffset")
    
    }
  
}
